package com.gaga.console.core.service.impl.ai;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MessageManager;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gaga.common.result.AiModelApiResult;
import com.gaga.console.core.entity.dto.ChatDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

/**
 * @author liujia
 * @version 1.0
 * @date 2025/4/9-10:03
 */
@Slf4j
public class QwenAiHandler extends AbstractAiHandler {
    @Override
    public AiModelApiResult getAiOutMessage(ChatDto dto) {

        AiModelApiResult aiModelApiResult = new AiModelApiResult();
        aiModelApiResult.setIsSuceess(false);
        Generation gen = new Generation();
        //这里填写自己申请的APIKEY
        Constants.apiKey = dto.getToken();
        MessageManager msgManager = new MessageManager(10);

        String promptMessage = buildPromptMessage(dto);

        Message systemMsg = Message.builder().role(Role.SYSTEM.getValue()).content(dto.getLiveRoomDesc()).build();
        //这里填写对话内容
        Message userMsg = Message.builder().role(Role.USER.getValue()).content(promptMessage).build();
        msgManager.add(systemMsg);
        msgManager.add(userMsg);

//        log.info("Qwen润色接口参数=" + JSON.toJSONString(msgManager.get()));

        QwenParam param = QwenParam.builder().model(Generation.Models.QWEN_PLUS).messages(msgManager.get())
                .resultFormat(QwenParam.ResultFormat.MESSAGE)
                .topP(0.7)
                .topK(50)
                .temperature(0.7f)
                .enableSearch(true)
                .build();
        GenerationResult result = null;
        try {
            result = gen.call(param);
        } catch (Exception e) {
            log.error("Qwen润色失败==={}", e.getMessage());
            JSONObject jsonObject = JSON.parseObject(e.getMessage());
            aiModelApiResult.setResult(String.valueOf(jsonObject.get("message")));
        }
        if (result != null) {
            if (CollectionUtils.isNotEmpty(result.getOutput().getChoices())) {
                aiModelApiResult.setIsSuceess(true);
                aiModelApiResult.setResult(result.getOutput().getChoices().get(0).getMessage().getContent());
                log.info("润色之后的话:" + aiModelApiResult.getResult());
            }
        }
        return aiModelApiResult;
    }
}
